﻿namespace AddressBook.Business.Person
{
  #region "Using Statements"
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;

  using Csla;
  using Csla.Data;
  #endregion

  [Serializable]
  public class AddressList : ReadOnlyListBase<AddressList, AddressInfo>
  {
    #region  "Factory Methods"

    public static AddressList EmptyList()
    {
      return new AddressList();
    }

    public static AddressList GetAddressList()
    {
      return DataPortal.Fetch<AddressList>();
    }

    private AddressList()
    { /* require use of factory methods */ }

    #endregion

    #region  "Data Access"

    private void DataPortal_Fetch()
    {
      RaiseListChangedEvents = false;

			using (var ctx = ContextManager<AddressBook.Business.Model.AddressBookDataContext>.GetManager(AddressBook.Business.Model.Database.AddressBook))
			{
				var data = (from a in ctx.DataContext.Addresses
										group a by new { a.AddressLine1, a.AddressLine2, a.City } into g
										select g);

				this.IsReadOnly = false;

				foreach (var addresses in data)
				{
					var address = addresses.First();
					this.Add(new AddressInfo(address.Id, 
																	 address.AddressLine1, 
																	 address.AddressLine2, 
																	 address.City, 
																	 address.StateProvinceId, 
																	 address.PostalCode));
				}
				this.IsReadOnly = true;
			}

      RaiseListChangedEvents = true;
    }

    #endregion
  }
}
